package com.zhkj.txg.module.product.ui

import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.txg.R
import com.zhkj.txg.module.product.adapter.CommentListAdapter
import com.zhkj.txg.module.product.vm.CommentListViewModel
import kotlinx.android.synthetic.main.fragment_order_list.*

class CommentListFragment : ViewModelFragment<CommentListViewModel>() {

    companion object {
        private val TYPE = "type"
        private val GOODS_ID = "goodsId"
        fun newInstance(goodsId: Long, type: Int): Fragment = CommentListFragment().apply {
            arguments = bundleOf(TYPE to type, GOODS_ID to goodsId)
        }
    }

    private val commentAdapter = CommentListAdapter().apply {
        loadMoreModule?.setOnLoadMoreListener { viewModel.commentList(false) }
    }

    override fun setViewModel(): CommentListViewModel = createViewModel(false)
    override val layoutResId: Int = R.layout.fragment_order_list

    override fun initUI() {
        with(rvOrderList) {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = commentAdapter
            setBackgroundColor(ContextCompat.getColor(context, R.color.colorWhite))
        }
        commentAdapter.setEmptyView(R.layout.layout_empty_data)
        refreshOrder.setOnRefreshListener { initData() }
    }

    override fun initViewModel() {
        viewModel.goodsId = arguments?.getLong(GOODS_ID) ?: 0
        viewModel.type = arguments?.getInt(TYPE) ?: 0
        viewModel.commentListLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 判断加载状态
                    if (!it.loadMore) refreshOrder.finishRefresh()
                    else if (it.hasMore) commentAdapter.loadMoreModule?.loadMoreComplete()
                    else commentAdapter.loadMoreModule?.loadMoreEnd(true)
                    // 数据填充
                    if (it.loadMore) commentAdapter.addData(it.data)
                    else commentAdapter.setNewData(it.data)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    if (viewModel.page > 1) commentAdapter.loadMoreModule?.loadMoreFail()
                    else refreshOrder.finishRefresh(false)
                }
            }
        })
    }

    override fun initData() {
        viewModel.commentList(true)
    }
}